package com.etc.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author kalista
 * @Description 服务端
 * @Date 2021/5/27  17:17
 **/
@Slf4j
public class NettyServer {

    private final int port ;

    public NettyServer(int port) {
        this.port = port;
    }

    public void start(){

        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup group = new NioEventLoopGroup();


        try {
            ServerBootstrap sb = new ServerBootstrap();
            // 绑定线程
            sb.group(group,bossGroup)
                    .option(ChannelOption.SO_BACKLOG,1024)
                    // 指定使用channel
                    .channel(NioServerSocketChannel.class)
                    .localAddress(port)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel ch) throws Exception {
                            System.out.println("收到一个连接");
                            // websocket 在http之上
                            // websocket 协议本身就是基于http 协议。 所以我们要http解码器 粘包毡包
                            ch.pipeline().addLast(new HttpServerCodec());
                            // 以快得方式处理请求
                            ch.pipeline().addLast(new HttpObjectAggregator(8192));
                            ch.pipeline().addLast(new ChunkedWriteHandler());  // ws://127.0.0.1:8888/websocket
                            ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws","websocket",true,635536*10));

                            ch.pipeline().addLast(new MyWebSocketHandler());
                        }
                    });

            // 服务器异步创建绑定
            ChannelFuture sync = sb.bind().sync();
            log.info("Netty server：{}",port);
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}
